<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2023/6/17
 * Time: 15:07
 */
namespace app\index\controller;

use app\middleware\AdminCheck;
use app\middleware\Check;
use think\facade\Db;

class Car {

    protected $middleware = [
        Check::class => ['except' => ['getList', 'detail'] ]
    ];

    /**
     * 车辆列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getList(){
        validateParam('pageNo,pageSize,region_id','pageNo,pageSize,region_id');
        $param = input();
        $where = ['status' => 1];
        if (isset($param['energy_type']) && is_numeric($param['energy_type'])) {
            $where['energy_type'] = $param['energy_type'];
        }
        if (isset($param['model_type']) && is_numeric($param['model_type'])) {
            $where['energy_type'] = $param['model_type'];
        }
        if (isset($param['brand_id']) && is_numeric($param['brand_id'])) {
            $where['brand_id'] = $param['brand_id'];
        }
        if (isset($param['range_min']) && is_numeric($param['range_min'])) {
            $where[] = ['range', '>', $param['range_min']];
        }
        if (isset($param['range_max']) && is_numeric($param['range_max'])) {
            $where[] = ['range', '<', $param['range_min']];
        }
        $query = Db::name('cars')
            ->where($where);

        if (isset($param['car_name']) && !empty($param['car_name'])) {
            $query->whereLike('car_name', $param['car_name']);
        }
        if (isset($param['region_id']) && !empty($param['region_id'])) {
            $query->whereRaw(" id in (select car_id from car_nos where region_id = {$param['region_id']})");
        }
        $total = $query->count();
        $offset = makeOffset($param['pageNo'],$param['pageSize']);
        $list = $query
            ->field('*')
            ->limit($offset,$param['pageSize'])
            ->where($where)
            ->order('id desc')
            ->select()->toArray();
        foreach ($list as &$val) {
            if ($val['customize_attr']) {
                $val['customize_attr'] = json_decode($val['customize_attr'], true);
                $val['pics'] = json_decode($val['pics'], true);
            }
        }

        return success('车辆列表',['total'=>$total,'list'=>$list]);
    }

    /**
     * 车辆详情
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function detail(){
        validateParam('car_id','car_id');
        $param = input();
        $where = ['id' => $param['car_id'], 'is_deleted' => 0];
        $query = Db::name('cars')
            ->where($where);

        $data = $query
            ->field('*')
            ->where($where)
            ->find();

        if (empty($data)) {
            return error('车辆信息未找到');
        }
        if ($data['status'] == 0) {
            return error('车辆已下架');
        }
        $data['customize_attr'] = json_decode($data['customize_attr'], true);
        $data['pics'] = json_decode($data['pics'], true);

        return success('车辆详情', $data);
    }

    /**
     * 试驾员信息
     * @return \think\response\Json
     */
    public function testDriverInfo() {
        $where = [
            ['user_id', '=', uid()]
        ];
        $info = Db::name('car_drivers')->where($where)->field(['id', 'name', 'mobile', 'status', 'refuse_reason', 'region_id', 'car_type'])->find();
        if (empty($info)) {
            return success('试驾员信息', []);
        }
        $info['region_name'] = Db::table('region')->where('region_id', $info['region_id'])->value('region_name');

        return success('试驾员信息', $info);
    }

    /**
     * 申请试驾员
     * @return \think\response\Json
     */
    public function applyTestDriver() {
        validateParam('name,mobile,region_id,car_type','name,mobile,region_id,car_type');
        if (!($card = Db::name('user_cards')->where(['user_id' => uid()])->find())) {
            return error('请先完成实名认证');
        }

        $updateWhere = [['user_id', '=', uid()]];
        $driver = Db::name('car_drivers')->where($updateWhere)->find();
        if ($driver && isset($driver['status']) && $driver['status'] == 0) {
            return error('试驾员已申请,请等待审核');
        }

        $data['name'] = input('name');
        $data['mobile'] = input('mobile');
        $data['region_id'] = input('region_id');
        $data['car_type'] = input('car_type');
        $data['id_card_font'] = $card['id_card_font'];
        $data['id_card_back'] = $card['id_card_back'];
        $data['license'] = $card['license'];
        $data['user_id'] = uid();
        $data['status'] = 0;
        $data['source'] = 1;

        $where = [
            'mobile' => input('mobile'),
            ['user_id', '!=', uid()]
        ];
        if (Db::name('car_drivers')->where($where)->find()) {
            return error('试驾员已存在');
        }

        if ($driver) {
            $res = Db::name('car_drivers')->where($updateWhere)->save($data);
        } else {
            $res = Db::name('car_drivers')->insert($data);
        }

        return success('申请试驾员成功', $res);
    }
}